/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.arecieve.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeesite.common.entity.Page;
import com.jeesite.common.service.CrudService;
import com.jeesite.modules.arecieve.entity.Treceivable;
import com.jeesite.modules.arecieve.dao.TreceivableDao;
import com.jeesite.modules.arecieve.entity.TreceivableDetail;
import com.jeesite.modules.arecieve.dao.TreceivableDetailDao;

/**
 * 收款单Service
 * @author wsm
 * @version 2021-03-22
 */
@Service
@Transactional(readOnly=true)
public class TreceivableService extends CrudService<TreceivableDao, Treceivable> {
	
	@Autowired
	private TreceivableDetailDao treceivableDetailDao;
	
	/**
	 * 获取单条数据
	 * @param treceivable
	 * @return
	 */
	@Override
	public Treceivable get(Treceivable treceivable) {
		Treceivable entity = super.get(treceivable);
		if (entity != null){
			TreceivableDetail treceivableDetail = new TreceivableDetail(entity);
			treceivableDetail.setStatus(TreceivableDetail.STATUS_NORMAL);
			entity.setTreceivableDetailList(treceivableDetailDao.findList(treceivableDetail));
		}
		return entity;
	}
	
	/**
	 * 查询分页数据
	 * @param treceivable 查询条件
	 * @param treceivable.page 分页对象
	 * @return
	 */
	@Override
	public Page<Treceivable> findPage(Treceivable treceivable) {
		return super.findPage(treceivable);
	}
	
	/**
	 * 保存数据（插入或更新）
	 * @param treceivable
	 */
	@Override
	@Transactional(readOnly=false)
	public void save(Treceivable treceivable) {
		super.save(treceivable);
		// 保存 Treceivable子表
		for (TreceivableDetail treceivableDetail : treceivable.getTreceivableDetailList()){
			if (!TreceivableDetail.STATUS_DELETE.equals(treceivableDetail.getStatus())){
				treceivableDetail.setReceivableId(treceivable);
				if (treceivableDetail.getIsNewRecord()){
					treceivableDetailDao.insert(treceivableDetail);
				}else{
					treceivableDetailDao.update(treceivableDetail);
				}
			}else{
				treceivableDetailDao.delete(treceivableDetail);
			}
		}
	}
	
	/**
	 * 更新状态
	 * @param treceivable
	 */
	@Override
	@Transactional(readOnly=false)
	public void updateStatus(Treceivable treceivable) {
		super.updateStatus(treceivable);
	}
	
	/**
	 * 删除数据
	 * @param treceivable
	 */
	@Override
	@Transactional(readOnly=false)
	public void delete(Treceivable treceivable) {
		super.delete(treceivable);
		TreceivableDetail treceivableDetail = new TreceivableDetail();
		treceivableDetail.setReceivableId(treceivable);
		treceivableDetailDao.deleteByEntity(treceivableDetail);
	}
	
}